//
//  SJAddFromSSViewController.m
//  WSL
//
//  Created by CJ on 2017/11/28.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//

#import "SJAddFromSSViewController.h"

#import "SJWordItem.h"
#import "SJExtraItem.h"
#import "SJOneCell.h"
#import "SJCustomLayout.h"
#import "SJSpaceStationAddApi.h"
#import "SJSpaceStationDelApi.h"
#import "SJSpaceStationCancelApi.h"

#import "SJTreeHeaderView.h"

#import "SJSpaceStationListApi.h"
#import "SJAddFromSSApi.h"

@interface SJAddFromSSViewController () <UICollectionViewDataSource, UICollectionViewDelegate, SJCustomLayoutDelegate>


////////////////////////////////////

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) int page;

@property (strong, nonatomic) SJCustomLayout *customLayout;
@property (nonatomic, strong) SJWordItem *selectedItem;

/////////  navigationBar
@property (nonatomic, strong) UIView *navigationBarView;

@end

@implementation SJAddFromSSViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [SJStatisticTool beginLogPageView:NSStringFromClass([self class])];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [SJStatisticTool endLogPageView:NSStringFromClass([self class])];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    NSString *imageName = @"guide_cutboard_return";
    if (812 == SJScreenH) {
        imageName = [NSString stringWithFormat:@"%@-x", imageName];
    }
    
    if ([SJGuideView shouldShowGuider:imageName] && self.dataArray.count == 0) {
        [SJGuideView guideViewWithImageName:imageName];
    }
}


- (void)dealloc {
    SJLogFunc;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.page = 0;
    [self setupUI];
    [self loadNewData];
}

- (void)setupUI {
    
    [self.view addSubview:self.collectionView];
    self.collectionView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    
    [self.view addSubview:self.navigationBarView];
    
    if (812 == SJScreenH) {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(40))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    } else {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(0))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    }
    
}

#pragma mark - getter


- (UIView *)navigationBarView{
    
    if (!_navigationBarView) {
        
        
        _navigationBarView = [UIView new];
        _navigationBarView.backgroundColor = [UIColor clearColor];
        
        // 返回
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [backButton setImage:[UIImage imageNamed:@"addtext-icon-return"] forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navigationBarView addSubview:backButton];
        backButton.sd_layout
        .centerYEqualToView(_navigationBarView)
        .leftSpaceToView(_navigationBarView, SJLayoutFrame(10))
        .heightIs(SJLayoutFrame(30))
        .widthIs(SJLayoutFrame(30));
        
        // 词条输入
        UILabel *wordLabel = [UILabel new];
        wordLabel.textColor = SJColorHexString(@"#ffffff");
        wordLabel.font = [UIFont fontWithName:@"Helvetica" size:SJLayoutFrame(17)];
        wordLabel.textAlignment = NSTextAlignmentCenter;
        wordLabel.text = @"剪切板";
        
        [_navigationBarView addSubview:wordLabel];
        wordLabel.sd_layout
        .centerYEqualToView(_navigationBarView)
        .centerXEqualToView(_navigationBarView)
        .heightIs(SJLayoutFrame(27));
        [wordLabel setSingleLineAutoResizeWithMaxWidth:SJScreenW * .5];
        
        // 确定
        UIButton *affirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [affirmButton setImage:[UIImage imageNamed:@"addtext_icon_confirm"] forState:UIControlStateNormal];
        [affirmButton addTarget:self action:@selector(uploadAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navigationBarView addSubview:affirmButton];
        affirmButton.sd_layout
        .centerYEqualToView(_navigationBarView)
        .rightSpaceToView(_navigationBarView, SJLayoutFrame(20))
        .heightIs(SJLayoutFrame(30))
        .widthIs(SJLayoutFrame(60));
        
    }
    
    return _navigationBarView;
}

- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)uploadAction {
    
    if (!self.selectedItem) {
        
        [SVProgressHUD showInfoWithStatus:@"请选择一个"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    int selectedW = [self.selectedItem.w intValue];
    int selectedH = [self.selectedItem.h intValue];
    
    BOOL isContain = NO;
    
    for (NSMutableDictionary *dict in self.optionArray) {
        
        if ([dict[@"w"] intValue] >= selectedW && [dict[@"h"] intValue] >= selectedH) {
            isContain = YES;
            break;
        } else {
        }
    }
    
    if (!isContain) {
        
        [SVProgressHUD showErrorWithStatus:@"空间太小"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"ss_id"] = self.selectedItem.ID;
    parameters[@"des_id"] = self.item?self.item.ID:@"0";
    parameters[@"l"] = self.l;
    parameters[@"t"] = self.t;
    
    SJAddFromSSApi *api = [[SJAddFromSSApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            SJWordItem *item = [SJWordItem modelWithJSON:api.responseObject[@"content"]];
            item.arrow = @"0";
            
            if (self.item) {
                [[NSNotificationCenter defaultCenter] postNotificationName:SJDidAddOneWordNotification object:nil userInfo:@{@"item": item}];
            } else {
                [[NSNotificationCenter defaultCenter] postNotificationName:SJDidAddZeroWordNotification object:nil userInfo:@{@"item": item}];
            }
            
            [self.navigationController popViewControllerAnimated:YES];
            
        } else {
            
            
        }
        
    } failure:^(YTKBaseRequest *request) {
        
    }];
   
}


- (NSMutableArray *)dataArray {
    
    if (!_dataArray) {
        
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (UICollectionView *)collectionView {
    
    if (!_collectionView) {
        
        // 首页
        self.customLayout = [[SJCustomLayout alloc] init];
        self.customLayout.delegate = self;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:self.customLayout];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.contentInset = UIEdgeInsetsMake(SJLayoutFrame(57), 0, 0, 0);
        
        [_collectionView registerClass:[SJOneCell class] forCellWithReuseIdentifier:NSStringFromClass([SJOneCell class])];
//        [_collectionView registerClass:[SJTreeHeaderView class] forSupplementaryViewOfKind:SJ_UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([SJTreeHeaderView class])];
        
        // header
        _collectionView.mj_header = [SJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        // footer
        _collectionView.mj_footer = [SJDIYFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
        _collectionView.allowsMultipleSelection = YES;
    }
    
    return _collectionView;
}

#pragma mark - SJCustomLayoutDelegate

- (CGRect)collectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout frameOfItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJWordItem *item = self.dataArray[indexPath.item];
    
    int lNum = [item.l intValue];
    int tNum = [item.t intValue];
    int wNum = [item.w intValue];
    int hNum = [item.h intValue];
    
    CGFloat x = lNum * SJItemWH + (lNum + 1) * SJMargin;
    CGFloat y = tNum * SJItemWH + (tNum + 0) * SJMargin; // 设置上面的 margin
    CGFloat w = wNum * SJItemWH + (wNum - 1) * SJMargin;
    CGFloat h = hNum * SJItemWH + (hNum - 1) * SJMargin;
    
    return CGRectMake(x, y, w, h);
}

- (CGFloat)bottomMarginInCollectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout {
    
    return SJMargin;
}


//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout heightForHeaderInSection:(NSInteger)section {
//    
//    int hNum = 2;
//    
//    CGFloat h = hNum * SJItemWH + (hNum - 1) * SJMargin;
//    
//    return h + 2 * SJMargin;
//}


#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate

//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
//
//    if ([kind isEqualToString:SJ_UICollectionElementKindSectionHeader]) {
//
//        SJTreeHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:SJ_UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([SJTreeHeaderView class]) forIndexPath:indexPath];
//
//        SJWordItem *item = [SJWordItem new];
//        item.w = @"2";
//        item.h = @"2";
//        item.fmt = @"10";
//
//        int wNum = [item.w intValue];
//        int hNum = [item.h intValue];
//        CGFloat w = wNum * SJItemWH + (wNum - 1) * SJMargin;
//        CGFloat h = hNum * SJItemWH + (hNum - 1) * SJMargin;
//        header.contentSize = CGSizeMake(w, h);
//
//        header.item = item;
//
//        return header;
//
//    } else if ([kind isEqualToString:SJ_UICollectionElementKindSectionFooter]){
//
//        return nil;
//    }
//
//    return nil;
//}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    // 根据数据量显示或者隐藏footer
    self.collectionView.mj_footer.hidden = (self.dataArray.count == 0);
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJOneCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([SJOneCell class]) forIndexPath:indexPath];
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
    cell.isChoosing = @"1";
    cell.item = item;
    
    WeakSelf;
    cell.singleTapLabel = ^(UICollectionViewCell *cell) {
        
        [weakSelf singleTap:cell];
    };
    
    cell.doubleTapLabel = ^(UICollectionViewCell *cell) {
        
        [weakSelf doubleTap:cell];
    };
    
    return cell;
}

#pragma mark 点击 cell 的事件
- (void)doubleTap:(UICollectionViewCell *)cell {
    
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    
    if (indexPath.row >= self.dataArray.count) {
        return;
    }
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
    if ([item.fmt isEqualToString:@"8"]) {
        return;
    }
    
//    SJTreeViewController *treeVC = [SJTreeViewController new];
//    treeVC.pageType = @"ss";
//    treeVC.item = item;
//    [self.navigationController pushViewController:treeVC animated:YES];
}

- (void)singleTap:(UICollectionViewCell *)cell {
    
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    
    if (indexPath.row >= self.dataArray.count) {
        return;
    }
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
//    if ([item.fmt isEqualToString:@"8"]) {
//        return;
//    }
    
    for (SJWordItem *item in self.dataArray) {
        item.isSelected = NO;
    }
    item.isSelected = YES;
    
    self.selectedItem = item;
    
    [self.collectionView reloadData];
}

#pragma mark - request

- (void)loadNewData {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = @"0";
    
    SJSpaceStationListApi *api = [[SJSpaceStationListApi alloc] initWithParameters:parameters];
    
    if ([api loadCacheWithError:nil]) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            self.dataArray = [[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            [self getItemOrigin];
            
        } else {
            [self.dataArray removeAllObjects];
        }
    }
    
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            self.dataArray = [[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            [self getItemOrigin];
            
        } else {
            [self.dataArray removeAllObjects];
        }
        
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
    }];
    
}

- (void)loadMoreData {

    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = [NSString stringWithFormat:@"%d", ++self.page];
    
    SJSpaceStationListApi *api = [[SJSpaceStationListApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            [self.dataArray addObjectsFromArray:[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"]]];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            [self getItemOrigin];
            
        } else {
            self.page--;
        }
        
        [self.collectionView reloadData];
        [self.collectionView.mj_footer endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        [self.collectionView reloadData];
        [self.collectionView.mj_footer endRefreshing];
        self.page--;
    }];
}


- (void)getItemOrigin {
    
    // 为每个 item 设置 l、t。
    int startT = 0;
    for (SJWordItem *item in self.dataArray) {
        
        item.t = [NSString stringWithFormat:@"%d", startT];
        item.l = @"0";
        
        int h = [item.h intValue];
        startT += h;
    }
}

@end

